package com.qys.training.biz.alive.listener;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Set;

/**
 * @author Winstone
 * @date 2020/8/5 - 8:36 下午
 */
public class OfflineListener implements Runnable {
    public static final Logger logger = LoggerFactory.getLogger(OfflineListener.class);
    private HazelcastInstance instance;

    public OfflineListener(HazelcastInstance instance) {
        this.instance = instance;
    }

    public void run() {
        offlineListener();
    }

    public void offlineListener() {
        IMap map = instance.getMap("aliveMap");
        IMap aliveList = instance.getMap("aliveList");
        if (aliveList.size() == 0 || map.size() == 0) {
            logger.info("[当前没有链接]---->{}", new Date());
        } else {
            Set<String> set = aliveList.keySet();
            for (String key : set) {
                String res = (String) map.get(key);
                if (res == null) {
                    logger.info("[{}]连接已断开----->{}", key, new Date());
                    aliveList.remove(key);
                }
            }
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        offlineListener();
    }
}
